﻿using System;
using System.ComponentModel.DataAnnotations;

namespace Lari.Services.Validation
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
    public class RequiredEitherOrAttribute : ValidationAttribute
    {
        private readonly string _firstProperty;
        private readonly string _secondProperty;
       
        public RequiredEitherOrAttribute(string firstProperty, string secondProperty)
        {
            _firstProperty = firstProperty;
            _secondProperty = secondProperty;
           
        }
      
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

            var firstPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(_firstProperty);
            if (firstPropertyInfo == null)
                throw new InvalidOperationException("Unknown property:" + _firstProperty);

            var secondPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(_secondProperty);
            if (secondPropertyInfo == null)
                throw new InvalidOperationException("Unknown property:" + _secondProperty);

            var firstPropertyValue = firstPropertyInfo.GetValue(validationContext.ObjectInstance, null);
            var secondPropertyValue = secondPropertyInfo.GetValue(validationContext.ObjectInstance, null);

            bool firstPropertyIsEmpty = firstPropertyValue == null ||firstPropertyValue.ToString().Trim().Length == 0;

            bool secondPropertyIsEmpty = secondPropertyValue == null ||secondPropertyValue.ToString().Trim().Length == 0;

            if (firstPropertyIsEmpty && secondPropertyIsEmpty)
            {
                return new ValidationResult(ErrorMessage);
            }
            if(!firstPropertyIsEmpty && !secondPropertyIsEmpty)
            {
                return new ValidationResult(ErrorMessage);
            }
            
            return ValidationResult.Success;
        }


    } 
}
